package com.easyedu.dean.service;

import com.easyedu.core.entity.BaseError;
import com.easyedu.core.entity.DbError;
import com.easyedu.core.entity.DeanServiceError;
import com.easyedu.core.entity.po.CultivationScheme;
import com.easyedu.core.exception.EasyEduException;
import com.easyedu.core.dao.CourseDao;
import com.easyedu.core.dao.CultivationSchemeDao;
import com.easyedu.dean.entity.dto.request.ReqCultivationScheme;
import com.easyedu.dean.entity.dto.request.ReqCultivationScheme.Course;
import com.easyedu.dean.entity.dto.response.RespQueryCultivationSchemeList;
import com.easyedu.core.utils.DoubleUtil;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author lmr
 **/
@Service
public class CultivationSchemeService {

     private static final String STR_FORMAT_2 = "00";
     private static final String STR_FORMAT_3 = "000";
     private static final String STR_FORMAT_4 = "0000";

     private final CultivationSchemeDao cultivationSchemeDao;
     private final InstituteService     instituteService;
     private final CourseService        courseService;

     public CultivationSchemeService(CultivationSchemeDao cultivationSchemeDao, CourseDao courseDao,
                                     InstituteService instituteService, CourseService courseService) {

          this.cultivationSchemeDao = cultivationSchemeDao;
          this.instituteService = instituteService;
          this.courseService = courseService;
     }

     @Transactional(rollbackFor = Exception.class)
     public void createCultivationScheme(ReqCultivationScheme schemeQuery) {

          String cultivationName = schemeQuery.getCultivationName();
          long belongDepartmentId = schemeQuery.getBelongDepartmentId();
          String belongDepartmentName = schemeQuery.getBelongDepartmentName();
          long belongInstituteId = schemeQuery.getBelongInstituteId();
          String belongInstituteName = schemeQuery.getBelongInstituteName();
          String grade = schemeQuery.getGrade();

          //判断是否存在学院和专业
          instituteService.hasInstitute(belongInstituteId, belongInstituteName);
          instituteService.hasDepartment(belongInstituteId, belongDepartmentId, belongDepartmentName);

          //生成培养计划名称 PYJH + 三位数学院id + 三位数专业id + 年级
          DecimalFormat decimalFormat = new DecimalFormat(STR_FORMAT_3);
          String departmentFormat = decimalFormat.format(belongDepartmentId);
          String instituteFormat = decimalFormat.format(belongInstituteId);
          String cultivationNumber = "PYJH" + instituteFormat + departmentFormat + grade;

          //判断是否已存在培养方案
          if (hasCultivationSchemeByNumber(cultivationNumber)) {
               throw new EasyEduException(DeanServiceError.ERR_CULTIVATION_SCHEME_EXIST);
          }

          List<Course> courses = schemeQuery.getCourses();
          for (Course course : courses) {
               //判断课程是否存在
               if (!courseService.hasCourse(course.getCourseId())) {
                    throw new EasyEduException(DeanServiceError.ERR_BASE_COURSE_CODE_NOT_EXIST,
                            "培养方案中存在一个未知课程，id为：" + course.getCourseId());
               }
               if (!DoubleUtil.isBefore0to1(course.getUsualScoreRatio(), course.getExperimentScoreRatio(),
                       course.getExamScoreRatio())) {
                    throw new EasyEduException(BaseError.ERR_PARA, "成绩占比必须是[0,1]之间的数字");
               }
               Integer isCommit = cultivationSchemeDao.createCultivationScheme(cultivationNumber, cultivationName,
                       belongInstituteId, belongInstituteName, belongDepartmentId, belongDepartmentName, grade,
                       course.getSchoolYear(), course.getSemester(), course.getTheoryClassHour(),
                       course.getExperimentClassHour(), course.getTotalClassHour(), course.getUsualScoreRatio(),
                       course.getExperimentScoreRatio(), course.getExamScoreRatio(), course.getNote(),
                       course.getCourseId());
               if (isCommit != 1) {
                    throw new EasyEduException(DbError.Err_INSERT_DB_ERROR, "新增培养方案失败");
               }
          }
     }

     /**
      * 判断是否存在培养方案
      *
      * @param cultivationNumber 培养方案序号
      * @return 是否存在
      */
     private boolean hasCultivationSchemeByNumber(String cultivationNumber) {

          List<CultivationScheme> cultivationSchemeList =
                  cultivationSchemeDao.getCultivationSchemeByNumber(cultivationNumber);

          return cultivationSchemeList != null && cultivationSchemeList.size() != 0;
     }

     public List<CultivationScheme> getCultivationSchemeCourse(String cultivationNumber) {

          return cultivationSchemeDao.getCultivationSchemeCourse(cultivationNumber);
     }

     public List<RespQueryCultivationSchemeList> getCultivationScheme(String grade) {

          if (Integer.parseInt(grade) <= 0) {
               throw new EasyEduException(BaseError.ERR_PARA, "年级不能为空或为负数");
          }
          List<CultivationScheme> cultivationScheme = cultivationSchemeDao.getCultivationScheme(grade);
          List<RespQueryCultivationSchemeList> resp = new ArrayList<>();
          for (CultivationScheme s : cultivationScheme) {
               RespQueryCultivationSchemeList r = new RespQueryCultivationSchemeList();
               BeanUtils.copyProperties(s, r);
               resp.add(r);
          }
          return resp;
     }
}
